package cameracontrol;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import se.lth.cs.realtime.JThread;
import se.lth.cs.realtime.RTThread;

/**
 * A RTThread which connects to a CameraServer. The thread sends request at
 * given intervalls. The period in which the thread sends request can be changed
 * by using the method setPeriod. When a request is received at the server side,
 * a picture is sent.
 */
public class CameraController extends JThread {
	private Socket socket;
	private PrintWriter out;
	private long period;
	private boolean run = true;

	/**
	 * Iniziates the connection to the CameraServer.
	 * 
	 * @param period
	 *            the starting period, by which request will be sent.
	 * @param ip
	 *            the ip adress of the CameraServer
	 * @param port
	 *            the port of the CameraServer
	 * @throws IOException
	 * @throws UnknownHostException
	 */
	public CameraController(long period, String ip, int port)
			throws UnknownHostException, IOException {
		this.period = period;
		socket = new Socket(ip, port);
		out = new PrintWriter(socket.getOutputStream(), true);
	}

	/**
	 * A picture is requested every period.
	 */
	@Override
	public void run() {
		while (run) {
			out.println("GIEF");
			try {
				snooze(period);
			} catch (InterruptedException e) {

			}
		}
	}

	private synchronized void snooze(long period) throws InterruptedException {
		wait(period);
	}

	public synchronized void wake() {
		notifyAll();
	}

	public synchronized void setPeriod(int period) {
		this.period = period;
	}

	public void kill() {
		run = false;
		try {
			socket.close();
		} catch (IOException e1){}
		wake();
		try {
			this.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
